﻿Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO

Namespace helper
    ''' <summary>
    ''' provides methods due with image objecy
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class ImageHelper
        ''' <summary>
        ''' Get Mime Type by Image
        ''' </summary>
        ''' <param name="i">image</param>
        ''' <returns>return image mime type</returns>
        ''' <remarks></remarks>
        Public Shared Function GetMimeType(ByVal i As Image) As String
            For Each codec As ImageCodecInfo In ImageCodecInfo.GetImageDecoders()
                If codec.FormatID = i.RawFormat.Guid Then
                    Return codec.MimeType
                End If
            Next

            Return "image/unknown"
        End Function

        ''' <summary>
        ''' get extension type from mime type
        ''' </summary>
        ''' <param name="mimeType">mime type</param>
        ''' <returns>return extension type with dot</returns>
        ''' <remarks></remarks>
        Public Shared Function GetExtension(ByVal mimeType As String) As String
            Select Case mimeType
                Case "image/gif"
                    Return ".gif"
                Case "image/jpeg", "image/pjpeg"
                    Return ".jpg"
                Case "image/png"
                    Return ".png"
            End Select

            Return ""
        End Function


        ''' <summary>
        ''' convert image to byte array
        ''' </summary>
        ''' <param name="imageIn">image</param>
        ''' <returns>image in byte array</returns>
        ''' <remarks></remarks>
        Public Function imageToByteArray(ByVal imageIn As System.Drawing.Image) As Byte()
            Dim ms As New MemoryStream()
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
            Return ms.ToArray()
        End Function

        ''' <summary>
        ''' convert byte array to image
        ''' </summary>
        ''' <param name="byteArrayIn">byte array</param>
        ''' <returns>image</returns>
        ''' <remarks></remarks>
        Public Function byteArrayToImage(ByVal byteArrayIn As Byte()) As Image
            Dim ms As New MemoryStream(byteArrayIn)
            Dim returnImage As Image = Image.FromStream(ms)
            Return returnImage
        End Function
    End Class


End Namespace

